package com.symaster.backups.frame.dialog;

import com.symaster.backups.frame.element.layout.TileLayout;
import com.symaster.backups.manager.EventManager;
import com.symaster.backups.model.FileSystemMonitorModel;
import com.symaster.backups.repository.FileSystemMonitorRepository;
import com.symaster.common.swing.util.SwingUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.io.File;
import java.util.Date;
import java.util.Optional;

/**
 * @author yinmiao
 * @version 2024/2/6
 */
@Component
public class AddMonitorFolderDialog extends JDialog implements ListDataListener {
    private final ComboBoxModel<ComboBoxEnum> comboBoxModel;
    private final JTextField pathInput;
    private final FileSystemMonitorRepository fileSystemMonitorRepository;
    private final EventManager eventManager;

    @Autowired
    public AddMonitorFolderDialog(FileSystemMonitorRepository fileSystemMonitorRepository,
                                  EventManager eventManager) {
        this.fileSystemMonitorRepository = fileSystemMonitorRepository;
        this.eventManager = eventManager;
        this.setTitle("添加备份");
        this.setModalityType(ModalityType.APPLICATION_MODAL);

        JPanel root = new JPanel();
        root.setBorder(new EmptyBorder(10, 10, 10, 10));
        root.setLayout(new BorderLayout(0, 5));

        JPanel rootPanel = new JPanel();
        rootPanel.setLayout(new TileLayout());
        root.add(rootPanel);

        JPanel jPanel1 = new JPanel();
        jPanel1.setLayout(new FlowLayout(FlowLayout.RIGHT, 15, 0));

        JButton jButton1 = new JButton("取消");
        jButton1.addActionListener(e -> dispose());
        jPanel1.add(jButton1);

        JButton jButton2 = new JButton("确定");
        jButton2.addActionListener(e -> create());
        jPanel1.add(jButton2);

        root.add(jPanel1, BorderLayout.SOUTH);

        this.setContentPane(root);

        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BorderLayout(5, 5));
        this.comboBoxModel = new DefaultComboBoxModel<>(new ComboBoxEnum[]{ComboBoxEnum.FILE, ComboBoxEnum.FOLDER});
        this.comboBoxModel.addListDataListener(this);
        jPanel.add(new JComboBox<>(comboBoxModel), BorderLayout.WEST);

        this.pathInput = new JTextField();
        jPanel.add(this.pathInput, BorderLayout.CENTER);

        JButton jButton = new JButton(SwingUtil.loadIcon("folder.png", 13, 13));
        jButton.setMargin(new Insets(0, 5, 0, 5));
        jButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();

            if (this.comboBoxModel.getSelectedItem() == ComboBoxEnum.FOLDER) {
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            } else if (this.comboBoxModel.getSelectedItem() == ComboBoxEnum.FILE) {
                fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            }

            int returnVal = fileChooser.showOpenDialog(AddMonitorFolderDialog.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                this.pathInput.setText(file.getAbsolutePath());
            }

        });
        jPanel.add(jButton, BorderLayout.EAST);

        rootPanel.add(jPanel);
    }

    private void create() {
        String text = pathInput.getText();

        if (StringUtils.isNotEmpty(text)) {
            File file = new File(text);
            if (!file.exists()) {
                JOptionPane.showMessageDialog(this, "指定路径不存在", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String pathName = file.toPath().toString();
            FileSystemMonitorModel model;
            Optional<FileSystemMonitorModel> oneByPathName = fileSystemMonitorRepository.findOneByPathName(pathName);
            if (oneByPathName.isPresent()) {
                FileSystemMonitorModel fileSystemMonitorModel = oneByPathName.get();
                if (!fileSystemMonitorModel.getDeleteStatus()) {
                    JOptionPane.showMessageDialog(this, "指定目录已加入自动备份目录, 请不要重复添加", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                model = fileSystemMonitorModel;
            } else {
                model = new FileSystemMonitorModel();
            }

            model.setDeleteStatus(false);
            model.setMonitor(true);
            model.setCreatedTime(new Date());
            model.setUpdatedTime(null);
            model.setStatus(1);
            model.setPathName(pathName);
            fileSystemMonitorRepository.save(model);

            dispose();

            /* 刷新列表 */
            eventManager.trigger("RELOAD_BACKUP_VIEW", null);
        }
    }

    @Override
    public void setVisible(boolean b) {
        resetSelectModel();
        super.setVisible(b);
    }

    private void resetSelectModel() {
        comboBoxModel.setSelectedItem(ComboBoxEnum.FOLDER);

    }

    @Override
    public void intervalAdded(ListDataEvent e) {

    }

    @Override
    public void intervalRemoved(ListDataEvent e) {

    }

    @Override
    public void contentsChanged(ListDataEvent e) {
        if (e.getSource() instanceof ComboBoxModel<?> comboBox) {
            if (comboBox.getSelectedItem() instanceof ComboBoxEnum comboBoxEnum) {
                pathInput.setText(null);


            }
        }

    }

    private enum ComboBoxEnum {
        FILE("单个文件"),
        FOLDER("文件夹");

        private final String label;

        ComboBoxEnum(String label) {
            this.label = label;
        }

        @Override
        public String toString() {
            return label;
        }
    }
}
